package net.huashitong.ssydt.provider.qiniu.utils;

import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import net.huashitong.ssydt.provider.qiniu.conifg.QiniuConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;

/**
 *
 */
public class QiniuUtils {

    private static Logger logger = LoggerFactory.getLogger(QiniuUtils.class);
    /**
     * 最简单的上传凭证
     * @return
     */
    public static String getSimpleUpToken(){
        Auth auth = Auth.create(QiniuConfig.ACCESS_KEY, QiniuConfig.SECRET_KEY);
        String upToken = auth.uploadToken(QiniuConfig.BUCKET);
        return upToken;
    }

    /**
     * 七牛数据流上传
     * @param filename
     * @param data
     * @return
     */
    public static DefaultPutRet upload(String filename, byte[] data) throws QiniuException {
        //构造一个带指定Zone对象的配置类
        Configuration cfg = new Configuration(Zone.zone0());
        //...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
        //...生成上传凭证，然后准备上传
        String accessKey = QiniuConfig.ACCESS_KEY;
        String secretKey = QiniuConfig.SECRET_KEY;
        String bucket = QiniuConfig.BUCKET;
        //默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = filename;
        byte[] uploadBytes = data;
        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(uploadBytes);
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        try {
            Response response = uploadManager.put(byteInputStream,key,upToken,null, null);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            return putRet;
        } catch (QiniuException ex) {
            Response r = ex.response;
            logger.error("QiniuException1 : [{}]",r.toString());
            //System.err.println(r.toString());
            try {
                //System.err.println(r.bodyString());
                logger.error("QiniuException2 : [{}]",r.bodyString());
                throw ex;
            } catch (QiniuException ex2) {
                logger.error("QiniuException2 : [{}}[{}]",ex2.getMessage(), ex2.getStackTrace());
                throw ex2;
            }
        }
    }

}
